<template>
    <article class="rm">
        <el-dialog title="" :visible.sync="dialogFormVisible">
            <div class="rm-tit ub ub-ac">
                <div class="f28 c-wh fw500">{{i18n.t('layout.reg')}}</div>
                <!-- <p class="ub-f1 f14 tx-r" @click="switchType">{{type === 'phone' ? i18n.t('layout.emailReg') : i18n.t('layout.phoneReg')}}</p> -->
            </div>
            <el-form class="login-form p20" autoComplete="on" :model="formData" :rules="rules" ref="regForm" label-position="left">
                <el-form-item v-show="type === 'phone'" prop="phone">
                    <el-input :placeholder="i18n.t('layout.phonePlace')" v-model="formData.phone" autoComplete="on" class="input-with-select mt3">
                        <el-select v-model="formData.areaCode" slot="prepend">
                            <el-option v-for="item in countrys" :key="item.value" :label="item.label" :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">+{{ item.value }}</span>
                            </el-option>
                        </el-select>
                    </el-input>
                </el-form-item>
                <el-form-item v-show="type === 'email'" prop="email">
                    <el-input :placeholder="i18n.t('layout.emailPlace')" v-model="formData.email" class="bor75" clearable></el-input>
                </el-form-item>

                <!-- <div id="rcbox" class="mt20"></div> -->
                <el-form-item prop="code">
                    <div class=" ub reg-inline">
                        <el-input :placeholder="i18n.t('layout.codeEnter')" v-model="formData.code" clearable class="ub-f1 bor75" style="width: auto;"></el-input>
                        <el-button id="rcbox" plain class="ml20 bor75" :disabled="countDisabled">{{countDownText}}</el-button>
                    </div>
                </el-form-item>
                <el-form-item prop="pwd">
                    <el-input type="password" :placeholder="i18n.t('layout.pwdPlace')" class="bor75" v-model="formData.pwd" clearable></el-input>
                </el-form-item>
                <el-form-item prop="rpwd">
                    <el-input type="password" :placeholder="i18n.t('layout.confirmPwd')" class="bor75" v-model="formData.rpwd" clearable @keyup.enter.native="handleReg"></el-input>
                </el-form-item>
                <el-form-item prop="icode">
                    <el-input :placeholder="i18n.t('layout.inviteCode')" v-model="formData.icode" class="bor75" clearable></el-input>
                </el-form-item>
                <div class="ub ub-ac mt30">
                    <el-button type="primary" style="padding: 12px 90px;" class="bor75" :loading="loading" @click.native.prevent="handleReg">{{i18n.t('layout.reg')}}</el-button>
                    <div class="ub-f1 tx-r">
                        <a href="javascript:void(0)" class="c-blu f14" @click="jumpLogin"><span class="c-wh">已有账户？</span>去登录</a>
                    </div>
                </div>
            </el-form>
        </el-dialog>

    </article>
</template>

<script>
import i18n from 'src/i18n'

import LoginModal from 'components/user/LoginModal' 

import 'assets/js/riddler-sdk-0.2.1'
import { APIgetPhoneCode, APIgetEmailCode, APIsignup } from 'api'

import { validatePhone, validatEmail } from 'utils/validate'
export default {
    data(){
        const validateUsername = (rule, value, callback) => {
            if (this.type === 'phone' && !validatePhone(value)) {
                callback(new Error(i18n.t('layout.phoneValite')))
            } else {
                callback()
            }
        }
        const validateEmail = (rule, value, callback) => {
            if (this.type === 'email' && !validatEmail(value)) {
                callback(new Error(i18n.t('layout.emailValite')))
            } else {
                callback()
            }
        }
        const validatePass = (rule, value, callback) => {
            if (value.length < 5) {
                callback(new Error(i18n.t('layout.pwdValite')))
            } else {
                callback()
            }
        }

        return {
            i18n,
            dialogFormVisible: false,
            yunFlag: false,

            type: 'phone',  //注册方式  'phone' or 'email'

            countDisabled: false,
            countDownText: i18n.t('layout.getCode'),

            formData: {
                areaCode: '86',
                phone: '',
                code: '',
                pwd: '',
                rpwd: '' ,
                icode: '',
                email: ''
            },
            rules: {
                phone: [{ required: true, trigger: ['blur', 'change'], validator: validateUsername }],
                email: [{ required: true, trigger: ['blur', 'change'], validator: validateEmail }],
                pwd: [{ required: true, trigger: ['blur', 'change'], validator: validatePass }],
                rpwd: [{ required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {

                    if (value != this.formData.pwd){
                        callback(new Error(i18n.t('layout.rpwdPrompt')))
                    } else {
                        callback()
                    }
                } }],
                code: [{ required: true, trigger: ['blur', 'change'], message: i18n.t('layout.codePrompt')}],
                // icode: [{ required: true, trigger: ['blur', 'change'], message: '请输入邀请码'}]
            },
            loading: false,

            countrys: [
                { value: '86', label: '中国'},
                // { value: '84', label: i18n.t('global.Vietnamese')}
            ]
        }
    },
    components: {

    },
    computed: {

    },
    beforeDestroy: function(){

    },
    mounted(){

    },
    methods:{
        init(){ 

            // 云片图片验证初始化
            this.yunpianInit();
        },

        switchType(){
            this.type = this.type === 'phone' ? 'email' : 'phone';
        },

        showModal(){
            this.dialogFormVisible = true;
            
            if (this.yunFlag === true){
                return;
            }
            this.$nextTick(() => {
                this.init();
                this.yunFlag = true;
            })
        },

        hideModal(){
            this.dialogFormVisible = false;
        },

        yunpianInit(){
            let _self = this;
            // 初始化
            new YpRiddler({
                expired: 10,
                mode: 'dialog',
                container: document.getElementById('rcbox'),
                noButton: true,
                appId: '136cc634c6d743a5a0e4dba0c27165a1',
                version: 'v1',
                onError: function (param) {
                    if(param.code == 429) {
                        // alert('请求过于频繁，请稍后再试！')
                        _self.$message({
                            type: 'error',
                            message: i18n.t('layout.yrPrompt')
                        });
                        return
                    }
                    // 异常回调
                    // console.error('验证服务异常')
                    _self.$message({
                        type: 'error',
                        message: i18n.t('layout.yrError')
                    });
                },
                onSuccess: function (validInfo, close) {
                    // 成功回调
                    // alert(`验证通过！token=${validInfo.token}, authenticate=${validInfo.authenticate}`)
                    _self.$message({
                        type: 'success',
                        message: i18n.t('layout.yrSuccess')
                    });
                    _self.getCode(validInfo.token, validInfo.authenticate);
                    close()
                },
                onFail: function (code, msg, retry) {
                    // 失败回调
                    _self.$message({
                        type: 'error',
                        message: i18n.t('layout.yrFail')
                    });
                    retry()
                },
                beforeStart: function (next) {
                    if (!validatePhone(_self.formData.phone)){
                        _self.$message({
                            type: 'error',
                            message: i18n.t('layout.phoneValite')
                        });
                        return;
                    }
                    // console.log('验证马上开始')
                    next()
                },
                onExit: function() {
                    // 退出验证 （仅限dialog模式有效）
                    // console.log('退出验证')
                }
            })
        },

        getCode(token, authenticate){

            let ops = {
                token, 
                authenticate,
                status: 0   //注册时传0
            }
            
            let API;

            if (this.type === 'phone'){
                API = APIgetPhoneCode;
                ops.mobile = this.formData.phone;
                ops.areaCode = this.formData.areaCode;
            } else {
                API = APIgetEmailCode;
                ops.email = this.formData.email;
            }

            API(ops).then(res => {
                
                // 开始倒计时
                this.startCountDown();
            })
        },

        startCountDown(){

            let num = 60;
            this.countDownText = num + 's';
            this.countDisabled = true;
            let fn = () => {
                setTimeout(() => {

                    if (num > 0){
                        --num;
                        this.countDownText = num + 's';
                        fn();
                    } else {
                        this.countDisabled = false;
                        this.countDownText = i18n.t('layout.getCode');           
                    }

                }, 1000)
            }

            fn();

        },

        handleReg() {
            this.$refs.regForm.validate(valid => {
                if (valid) {
                    this.loading = true;

                    let ops = {
                        type: this.type === 'phone' ? 0 : 1,
                        password: this.formData.pwd,
                        vcode: this.formData.code,
                        iCode: this.formData.icode
                    }
                    if (this.type === 'phone'){
                        ops.account = this.formData.phone; 
                        ops.areaCode = this.formData.areaCode;
                    } else {
                        ops.account = this.formData.email; 
                    }
                    APIsignup(ops).then(res => {
                        this.loading = false;
                        this.$message({
                            type: 'success',
                            message: i18n.t('layout.regSuccess')
                        });
                        this.jumpLogin();
                    }, err => {
                        this.loading = false;
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        jumpLogin(){
            this.hideModal();
            this.$nextTick(() => {
                LoginModal.show();
            })
        }
    }
}

</script>

<style>
.bor75{border-radius: 75px;}

.rm .el-dialog{ width: 540px; }
.rm .el-select .el-input__inner {width: 120px;}
.rm .el-select-dropdown{width: 240px;}
.rm .el-form-item__content>.el-input-group, .rm .el-form-item__content .bor75>.el-input__inner{border-radius: 75px; overflow: hidden;}
</style>
<style lang="scss" scoped>
.rm-tit{
    border-bottom: 1px solid #192038; margin-bottom: 26px;
    &>div{
        padding: 0 17px 20px 17px; border-bottom: 2.5px solid #3366FF;
    }
    &>p{
        color: #1890FF;
    }
}
.reg-inline>*{display: block;}
</style>


